import { Controller, Get, Inject } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import * as svgCaptcha from 'svg-captcha';
import { ConfigService } from '@nestjs/config';
import { Util } from 'src/common/Util';
import { CacheUtil } from 'src/common/CacheUtil';
import { CacheKey } from 'src/common/CacheKey';
import { Constants } from 'src/common/Constants';
import SystemConfigService from '../service/SystemConfigService';

/*
 * @Author: jingfuu@163.com
 * @Date: 2024-11-08 11:17:50
 * @LastEditTime: 2024-12-11 12:42:04
 * @Description: 验证码
 */
@ApiTags('验证码')
@Controller('captchaImage')
export class CaptchaController {
  @Inject()
  configService: ConfigService;

  @Inject()
  systemConfigService: SystemConfigService;

  @ApiOperation({ summary: '获取验证码' })
  @Get()
  async getCaptcha() {
    const captchaEnabled =
      await this.systemConfigService.getUserCaptchaEnabled();
    const captchaExpiration =
      await this.systemConfigService.getUserCaptchaExpiration();
    const res = { captchaEnabled, code: Constants.SUCCESS };
    if (!captchaEnabled) {
      return res;
    }
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      noise: 2, // 干扰线条的数量
      width: 160,
      height: 60,
      fontSize: 50,
      color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
    });
    // 将 SVG 字符串转换为 Buffer
    const buffer = Buffer.from(captcha.data);
    res['img'] = buffer.toString('base64');
    res['uuid'] = Util.getUuid();
    CacheUtil.setCacheObject(
      CacheKey.USER_CAPTCHA + res['uuid'],
      captcha.text,
      60 * captchaExpiration,
    );
    return res;
  }
}
